﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.VisualStudio.Modeling;

namespace DSLFactory.VSCTDesigner
{
    partial class CommandBase
    {
        public IDSymbol GetIDSymbol()
        {
            GuidSymbol guid = this.CommandTable.Symbols.FirstOrDefault(s => s.Name == this.Guid);
            if( guid != null )
                return guid.IDSymbols.FirstOrDefault(i => i.Name == this.ID);
            return null;
        }

        internal string GetKeyBindingValue()
        {
            if( KeyBinding == null )
                return String.Empty;

            StringBuilder sb = new StringBuilder();
            if( KeyBinding.Mod1 != KeyModifier.None )
            {
                sb.Append(KeyBinding.Mod1);
                sb.Append("+");
            }
            if( !String.IsNullOrEmpty(KeyBinding.Key1) )
            {
                sb.Append(KeyBinding.Key1);
            }
            if( KeyBinding.Mod2 != KeyModifier.None )
            {
                if( !String.IsNullOrEmpty(KeyBinding.Key1) )
                    sb.Append(",");
                sb.Append(KeyBinding.Mod2);
                sb.Append("+");
            }
            if( !String.IsNullOrEmpty(KeyBinding.Key2) )
            {
                sb.Append(KeyBinding.Key2);
            }
            return sb.ToString();
        }

        public virtual bool CanAddKeyBinding
        {
            get { return this.KeyBinding == null; }
        }

        public virtual bool CanDeleteKeyBinding
        {
            get { return this.KeyBinding != null; }
        }

        public void AddKeyBinding()
        {
            using( Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add key binding") )
            {
                this.KeyBinding = new KeyBindingElement(Store);
                transaction.Commit();
            }
        }

        public void DeleteKeyBinding()
        {
            if( KeyBinding != null )
            {
                using( Transaction transaction = this.Store.TransactionManager.BeginTransaction("Add key binding") )
                {
                    this.KeyBinding.Delete();
                    transaction.Commit();
                }
            }
        }

        /// <summary>
        /// Gets the command table.
        /// </summary>
        /// <param name="store">The store.</param>
        /// <returns></returns>
        public CommandTable CommandTable
        {
            get
            {
                return Store.ElementDirectory.FindElements<CommandTable>().FirstOrDefault();
            }
        }
    }
}
